package com.ecp.commons.dao;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.ecp.commons.bean.IDS2;
import com.ecp.commons.db.MongoDAOImpl2;
import com.mongodb.BasicDBObject;

@Repository("idsMongo")
public class IDSMongoImpl extends MongoDAOImpl2<IDS2> implements IDSMongo {
	private static final int	STEP	= 100;							// 一次预取n个，减少数据库的读写次数
	private Map<String, IDS2>	mapIds	= new HashMap<String, IDS2>();

	@Override
	public synchronized long generateId(String tableName) throws Exception {
		IDS2 ids = mapIds.get(tableName);
		if ((ids == null) || (ids.getCurValue() >= ids.getNextValue() + STEP)) {
			ids = this.findAndModify(new BasicDBObject("tableName", tableName), new BasicDBObject("$inc",
					new BasicDBObject("nextValue", STEP)));
			if (ids == null) {
				throw new Exception("Generate id failed.");
			}
			ids.setCurValue(ids.getNextValue());
			mapIds.put(tableName, ids);
		}

		long newId = ids.getCurValue();
		ids.setCurValue(newId + 1);
		return newId;
	}

}